package com.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.bean.ChatBean;
import com.dao.IChatDao;

public class ChatDao extends SimpleJdbcDaoSupport implements IChatDao {
	
	//发言
	public int insertChat(ChatBean bean){
		int ret = 0;
		String sql = "insert into tb_chat(session_id,sequence,ename,cname,content) values(?,?,?,?,?)";
		Object[] args = new Object[]{bean.getSessionID(),bean.getSequence(),bean.getEname(),bean.getCname(),bean.getContent()};
		ret = getSimpleJdbcTemplate().update(sql, args);
		return ret;
	}
	
	//查询会话最大楼层号
	public int queryChatLayer(int sessionid){
		int ret = 0;
		String sql = "select max(sequence) from tb_chat where session_id=?";
		ret = getSimpleJdbcTemplate().queryForInt(sql, sessionid);
		return ret;
	}
	
	//查询会话内容 按照层号从大到小的顺序
	public List<ChatBean> queryChatDetail(int sessionid){
		String sql = "select * from tb_chat where session_id=? order by sequence desc";
		final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return getSimpleJdbcTemplate().query(sql, new ParameterizedRowMapper<ChatBean>(){
			public ChatBean mapRow(ResultSet rs, int index)
					throws SQLException {
				ChatBean bean = new ChatBean();
				bean.setId(rs.getInt("id"));
				bean.setSequence(rs.getInt("sequence"));
				bean.setEname(rs.getString("ename"));
				bean.setCname(rs.getString("cname"));
				bean.setContent(rs.getString("content"));
				bean.setJoinTime(format.format(rs.getTimestamp("joinTime")));
				return bean;
			}
		}, sessionid);
	}
}
